import json
import os
import shutil
import urllib
import urllib.request
import urllib.parse
import time
import datetime
import ssl
import socket
import subprocess

ssl._create_default_https_context = ssl._create_unverified_context
socket.setdefaulttimeout(15)  # 设置默认超时时间为10秒

is_rtmp_save = 1
rtmp_file_name = ''
ivs1800_cookie = ''
device_name = ''
# IVS1800 IP
ivs_ip = '222.134.135.210'
# IVS1800端口
ivs_port = '18531'
dev_id = ''
nvr_code = ''
start_time = ''
end_time = ''
rtsp_url = ''


def get_rstp_url():
    data = {
        "cameraCode": dev_id,
        "mediaURLParam": {
            "broadCastType": 0,
            "protocolType": 2,
            "serviceType": 1,
            "streamType": 1,
            "transMode": 0

        }
    }

    headers = {
        'Content-Type': 'application/json',
        'Cookie': ivs1800_cookie
    }
    data = bytes(json.dumps(data), 'utf8')
    url = 'https://%s:%s/video/rtspurl/v1.0' % (ivs_ip, ivs_port)
    request = urllib.request.Request(url=url, data=data, headers=headers, method='POST')
    response = urllib.request.urlopen(request)
    data = response.read()
    jsonData = json.loads(data)
    return jsonData["rtspURL"].replace("192.168.1.5", ivs_ip)


def parsing_data():
    global rtmp_file_name, is_rtmp_save, ivs1800_cookie, nvr_code, dev_id, start_time, end_time, rtsp_url, device_name
    while 1:
        for imageFile in os.listdir('rtsp_to_flv'):
            rtmp_file_name, extension = os.path.splitext(imageFile)
            with open('./rtsp_to_flv/' + imageFile, 'r') as file:
                lines = file.readlines()
                ivs1800_cookie = lines[0]
                device_name = [1]

            dev_id = imageFile.split('N')[0].replace('M', '#')
            nvr_code = dev_id.split('#')[1]
            image_date = imageFile.split('N')[1].split('.')[0]
            year = int(image_date[:4])
            month = int(image_date[4:6])
            day = int(image_date[6:8])
            hour = int(image_date[8:10])
            minute = int(image_date[10:12])
            second = int(image_date[12:14])
            _date = datetime.datetime(year, month, day, hour, minute, second)
            s_date = _date - datetime.timedelta(seconds=5)
            e_date = _date + datetime.timedelta(seconds=5)
            start_time = s_date.strftime('%Y%m%d%H%M%S')
            end_time = e_date.strftime('%Y%m%d%H%M%S')

            try:
                rtsp_url = get_rstp_url()
            except Exception as e:
                time.sleep(5)
                continue
            os.remove('./rtsp_to_flv/' + imageFile)
            # 输出FLV文件地址
            path = f'./video/{datetime.datetime(year, month, day, hour, minute, second).strftime(
                '%Y-%m-%d')}/{device_name}'
            if not os.path.exists(path):
                os.makedirs(path)


            # 构建ffmpeg命令
            ffmpeg_command = [
                'vlc.exe',
                '--intf', 'dummy',
                '--run-time', '1000'
                              '-vvv',  # 输入流地址
                rtsp_url,
                '--sout', '#standard{access=file,mux=ts,dst=%s}' % f'{path}/{rtmp_file_name}.flv',  # 输出格式为flvS
            ]
            try:
                # 运行ffmpeg命令
                subprocess.run(ffmpeg_command, timeout=10)
            except subprocess.TimeoutExpired:
                ffmpeg_command = [
                    'vlc.exe',
                    '-I', 'dummy',
                    f'{path}/{rtmp_file_name}.flv',
                    '--sout', '#transcode{vcodec=h264}:standard{access=file,mux=mp4,dst=%s}' % f'{path}/{rtmp_file_name}.mp4',
                    # 输出格式为flvS
                ]
                try:
                    subprocess.run(ffmpeg_command, timeout=15)
                except subprocess.TimeoutExpired:
                    print("转换完成")
                    # 转换完成删除flv文件
                    os.remove(f'{path}/{rtmp_file_name}.flv')

        time.sleep(2)


if __name__ == '__main__':
    parsing_data()
